﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ShenNius.Repository;
using ShenNius.Sys.API.Controllers;
using ShenNius.Sys.API.Dtos.Common;
using ShenNius.Sys.API.Infrastructure.Configs;
using ShenNius.Wechat.API.Domain.Entity;
using ShenNius.Wechat.API.Dtos;
using ShenNius.Wechat.API.Dtos.Input;
using ShenNius.Wechat.API.Infrastructure.Common;
using System.Collections.Generic;
using System.Threading.Tasks;


/*************************************
* 类名：WeixinController
* 作者：realyrare
* 邮箱：mahonggang8888@126.com
* 时间：2021/6/9 16:56:10
*┌───────────────────────────────────┐　    
*│　   版权所有：神牛软件　　　　	     │
*└───────────────────────────────────┘
**************************************/

namespace ShenNius.Wechat.API.Controllers
{
    public class SettingController : ApiTenantBaseController<Setting, DetailTenantQuery, DeletesTenantInput, KeyListTenantQuery, Setting, Setting>
    {
        private readonly IBaseRepository<Setting> _repository;
        private readonly WxBaseService _wxBaseService;
        private readonly HttpHelper _httpHelper;

        public SettingController(IBaseRepository<Setting> repository, IMapper mapper, WxBaseService wxBaseService, HttpHelper httpHelper) : base(repository, mapper)
        {
            _repository = repository;
            _wxBaseService = wxBaseService;
            _httpHelper = httpHelper;
        }
        /// <summary>
        /// 修改自定义菜单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> ModifyMenu([FromBody] WxMenuInput input)
        {
            var model = await _repository.GetModelAsync(m => m.Id == input.Id);
            if (model == null)
            {
                return new ApiResult("没有查找对应的公众号信息");
            }
            model.ChangeMenuJson(input.Menu);
            await _repository.UpdateAsync(model);
            return new ApiResult();
        }

        /// <summary>
        /// 同步到公众号菜单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> SyncMenu([FromBody] DetailTenantQuery query)
        {
            //获得公众号配置
            var model = await _repository.GetModelAsync(m => m.Id == query.Id);
            //获得access_taken
            var token = await _wxBaseService.GetAccessTokenAsync(model.AppId, model.AppSecret);
            var dbMenu = JsonConvert.DeserializeObject<List<WxButton>>(model.MenuJson);
            foreach (var item in dbMenu)
            {
                item.SubButton = item.SubButton.Count > 0 ? item.SubButton : null;
                if (item.Type == "0" && !string.IsNullOrEmpty(item.Url))
                {
                    item.Type = "view";
                }
                else if (item.Type == "1" && !string.IsNullOrEmpty(item.MediaId))
                {
                    item.Type = "media_id";
                    item.Url = null;
                }
                else
                {
                    item.Type = null;
                    item.Url = null;
                }
                if (item.SubButton != null)
                {
                    foreach (var row in item.SubButton)
                    {
                        if (row.Type == "0" && !string.IsNullOrEmpty(row.Url))
                        {
                            row.Type = "view";
                        }
                        else if (row.Type == "1" && !string.IsNullOrEmpty(row.MediaId))
                        {
                            row.Type = "media_id";
                            row.Url = null;
                        }
                        else
                        {
                            row.Type = null;
                            row.Url = null;
                        }
                    }
                }
            }
            JsonSerializerSettings jsetting = new JsonSerializerSettings();
            jsetting.NullValueHandling = NullValueHandling.Ignore;
            var body = JsonConvert.SerializeObject(new WxPushButton() { Button = dbMenu }, jsetting);
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}", token);
            var result = await _httpHelper.PostAsync<WxResult>(url, body);
            if (result.Errcode == 0)
            {
                return new ApiResult();
            }
            return new ApiResult(result.Errmsg, result.Errcode);
        }
    }
}